#!/usr/bin/env python
# coding=utf-8
import os
import re
import json
import sys

"""
:: http://wuyou.run/monitor/zabbix/ports.discovery.py
python port_discover.py
"""


def port_dict():
    drop_list = ['25', '111','sshd']
    # 排除指定端口或进程名
    drop_str = "|".join(drop_list)

    cmd = """sudo netstat -pntl | awk '/[0-9]\//{print $4,$7}'|sed  's/:$//' |sed 's_.*\:__' |sed 's#[ ][0-9].*\/#:#g'|sort |uniq | egrep -v '%s' """ % (drop_str)
    result_str = os.popen(cmd)
    # 返回结果 端口和进程名

    service_dict = {}

    for line in result_str:
        port_reg = re.search(r"(\d+)\:(\S+)", line)
        if port_reg is not None:
            match_line = (port_reg.groups())
            service_dict[match_line[-2]] = match_line[-1]
    # service_dict = check_custom_name(service_dict)
    return service_dict


def json_zabbix(args):
    ports = []
    for key in args:
        ports += [{'{#PNAME}': args[key], '{#PPORT}': key}]
    return json.dumps({'data': ports}, sort_keys=True, indent=4, separators=(',', ':'))
    # 格式化成适合zabbix lld的json数据


if __name__ == "__main__":
    local_port= port_dict()
    print(json_zabbix(local_port))

